package com.sun.servlet;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.Session;
import com.sun.dao.ReaderDao;
import com.sun.domain.Reader;
import com.sun.util.CaptchaUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author SunRui
 * @description reader servlet
 * @date 2024/7/4 21:09
 */
@WebServlet(urlPatterns = "/ReaderServlet.action")
public class ReaderServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(ReaderServlet.class);
    InputStream resource = Resources.getResourceAsStream("mybatisConfig.xml");
    //获取session工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);


    public ReaderServlet()  throws IOException{
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ReaderDao readerDao = sqlSession.getMapper(ReaderDao.class);
        String opr = req.getParameter("opr");
        String jsonString = null;
        String str = null;
        CaptchaUtil captchaUtil = new CaptchaUtil();//验证码方法
        //把验证码存放到session
        HttpSession session = req.getSession();
        switch (opr) {
            case "sendCaptcha"://登录验证码发送
                String captcha = captchaUtil.generateCaptcha();
                session.setAttribute("captcha", captcha);
                logger.debug("验证码:" + captcha);
                sqlSession.close();
                jsonString = JSON.toJSONString("ok");
                resp.getWriter().write(jsonString);
                break;
            case "login":
                String email = req.getParameter("email");
                String pwd = req.getParameter("pwd");
                String captcha2 = req.getParameter("captcha");
                logger.debug("登录邮箱:" + email + ";登录密码:" + pwd + ";登录验证码:" + captcha2);
                //提取验证码
                String captcha3 = (String) session.getAttribute("captcha");
                if (captchaUtil.captchaEquals(captcha3, captcha2)) {
                    session.removeAttribute("captcha");
                    Reader reader = readerDao.login(email, pwd);
                    if (reader != null) {
                        session.setAttribute("reader", reader);
                        logger.debug("登录的账号信息:" + reader.toString());
                        str = "ok";
                    } else {
                        str = "loginNo";
                    }
                } else {
                    str = "captchaNo";
                }
                sqlSession.close();
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
            case "register":
                String email2 = req.getParameter("email");
                String pwd2 = req.getParameter("pwd");
                String captcha4 = req.getParameter("captcha");
                String name = req.getParameter("name");
                logger.debug("注册名称:"+name+";注册邮箱:" + email2 + ";注册密码:" + pwd2 + ";注册验证码:" + captcha4);
                //提取验证码
                String captcha5 = (String) session.getAttribute("captcha");
                if (captchaUtil.captchaEquals(captcha5, captcha4)) {
                    session.removeAttribute("captcha");
                    Reader reader = new Reader();
                    reader.setName(name);
                    reader.setEmail(email2);
                    reader.setPwd(pwd2);
                    reader.setMoney(0);
                    reader.setBorrowSum(5);
                    if (readerDao.addReader(reader)>0){
                        str = "ok";
                        try{
                            //提交事务
                            sqlSession.commit();
                            logger.debug("注册事务:提交成功");
                        }catch (Exception e){
                            e.printStackTrace();
                            logger.debug("注册事务:提交失败("+e.getMessage()+")");
                            //回滚(出错了回滚)
                            sqlSession.rollback();
                        }finally {
                            sqlSession.close();
                        }
                    }else {
                        sqlSession.close();
                        str = "no";
                    }
                } else {
                    sqlSession.close();
                  str = "captchaNo";
                }
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
            case "myLoad":
                //获取登录的账号
                Reader reader = (Reader) session.getAttribute("reader");
                String emails = reader.getEmail();
                String pwds = reader.getPwd();
                Reader readers = readerDao.login(emails, pwds);
                logger.debug("提取的账号信息:"+readers);
                jsonString = JSON.toJSONString(readers);
                resp.getWriter().write(jsonString);
                break;
            case "topUpMoney":
                //充值
                int money = Integer.parseInt(req.getParameter("money"));
                logger.debug("前端传回充值数据:"+money);
                Reader reader1 = (Reader) session.getAttribute("reader");
                if (readerDao.topUpMoney(reader1.getEmail(),money)>0){
                    str = "ok";
                    try{
                        //提交事务
                        sqlSession.commit();
                        logger.debug("注册事务:提交成功");
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.debug("注册事务:提交失败("+e.getMessage()+")");
                        //回滚(出错了回滚)
                        sqlSession.rollback();
                    }
                }
                //将后台的用户信息刷新
                Reader reader3 = (Reader) session.getAttribute("reader");
                Reader reader2 = readerDao.login(reader3.getEmail(),reader3.getPwd());
                session.setAttribute("reader",reader2);
                sqlSession.close();
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
            case "changePwd":
                //密码修改
                String changePwd = req.getParameter("newPwd2");
                logger.debug("前端传回的新密码:"+changePwd);
                Reader reader4 = (Reader) session.getAttribute("reader");
                String oldPwd = req.getParameter("pwd");
                if (!oldPwd.equals(reader4.getPwd())){
                    str = "oldno";
                }else if (readerDao.updatePwd(reader4.getId(),changePwd)>0){
                    str = "ok";
                    try{
                        //提交事务
                        sqlSession.commit();
                        logger.debug("注册事务:提交成功");
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.debug("注册事务:提交失败("+e.getMessage()+")");
                        //回滚(出错了回滚)
                        sqlSession.rollback();
                    }
                }
                sqlSession.close();
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
